#!/bin/bash

# 检查firewalld服务状态
if ! systemctl is-active --quiet firewalld; then
    echo "[-] firewalld服务未运行"
    exit 1
fi

# 检查默认区域是否为安全区域
safe_zones="public drop block"
default_zone=$(firewall-cmd --get-default-zone 2>/dev/null)
if echo "$safe_zones" | grep -qw "$default_zone"; then
    echo "[+] 默认区域为安全区域: $default_zone"
else
    echo "[-] 默认区域($default_zone)不是安全区域"
    exit 1
fi

# 检查默认策略是否为DROP
default_target=$(firewall-cmd --permanent --get-target 2>/dev/null)
if [ "$default_target" = "DROP" ]; then
    echo "[+] 默认策略为DROP，已拒绝所有传入流量"
else
    echo "[-] 默认策略不是DROP，当前为: $default_target"
    exit 1
fi

# 检查 /etc/firewalld/firewalld.conf 是否存在并包含 DefaultZone=drop
conf_file="/etc/firewalld/firewalld.conf"
if [ -f "$conf_file" ]; then
    if grep -Eq '^[[:space:]]*DefaultZone=drop[[:space:]]*$' "$conf_file"; then
        echo "[+] 配置文件已包含 DefaultZone=drop"
    else
        echo "[*] 配置文件存在但未设置 DefaultZone=drop，追加设置"
        echo "DefaultZone=drop" | sudo tee -a "$conf_file" > /dev/null
    fi
else
    echo "[*] 配置文件不存在，创建并写入 DefaultZone=drop"
    echo "DefaultZone=drop" | sudo tee "$conf_file" > /dev/null
fi

# 重启 firewalld 使配置生效
sudo systemctl restart firewalld

echo "[+] firewalld配置检查通过"
exit 0